import { createRouter, createWebHistory } from "vue-router";

import Login from "@/views/login/login.vue";

import Index from "@/views/index.vue";

import Home from "@/views/home/home.vue";

import NotFound from "@/views/error/404.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/login",
      name: "root",
      component: Login,
      meta: {
        requireAuth: false,
      },
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: {
        requireAuth: false,
      },
    },
    {
      path: "/index",
      name: "index",
      component: Index,
      redirect: "/home/index",
      meta: {
        title: "首页",
      },
      children: [
        {
          path: "/home/index",
          name: "home",
          component: Home,
          meta: {
            requireAuth: true,
            title: "首页",
          },
        },
      ],
    },
    // 使用正则 404页面
    { path: "/:path(.*)", component: NotFound },
  ],
});

router.beforeEach(async (to, from, next) => {
  const token = window.localStorage.getItem("token");
  if (token) {
    // 如果是访问登录界面，如果用户会话信息存在，代表已登录过，跳转到主页
    if (to.path === "/login") {
      window.localStorage.removeItem("token");
    }
    // 否则跳转到正常跳转
    next();
  } else {
    // 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
    if (to.path === "/login") {
      // 否则跳转到正常跳转
      next();
    } else {
      if (to.meta.requireLogin == false) {
        next();
      } else {
        next({
          path: "/login",
          query: {
            redirect: to.fullPath,
          }, // 将跳转的路由path作为参数，登录成功后跳转到该路由
        });
      }
    }
  }
});

export default router;
